import { StyleSheet, Text, View, TouchableHighlight } from 'react-native'
import React, { useState, useEffect, useCallback } from 'react'
import {
  Center, Box, Heading, VStack, FormControl, Input,
  Link, HStack, Button
} from 'native-base'
import { globalPadding } from '../style'
import UploadFile from '../components/Upload/UploadFile'
import axios from '../axios'
import Picker from 'react-native-picker'

const UploadGoods = ({ navigation, route }) => {
  const id = route.params?.id
  useEffect(() => {
    navigation.setOptions({
      title: id ? '编辑商品' : '上传商品'
    })
    axios.get('/category').then(res => {
      setCategories(res.data)
      initPickerData(res.data)
    })
    if(id) {
      axios.get(`/goods/${id}`).then(res => {
        setData({
          ...res.data,
          category: res.data.category._id
        })
        setCategory(res.data.category.name)
      })
    }
    return () => {
      Picker.hide();
    }
  }, [id])
  const [categories, setCategories] = useState([])
  // const [firstColumn, setFirstColumn] = useState([])
  // const [secondColumn, setSecondColumn] = useState([])
  const [pickerData, setPickerData] = useState([])
  const [selectedValue, setSelectedValue] = useState([])
  const [category, setCategory] = useState('')

  const initPickerData = (list) => {
    // setFirstColumn(list.map(item => item.name))
    // setSecondColumn(list[0].children.map(item => item.name))
    const data = []
    list.forEach(item => {
      data.push({
        [item.name]: item.children.map(cItem => cItem.name)
      })
    })
    setPickerData(data)
    const defaultKey = Object.keys(data[0])[0]
    setSelectedValue([ defaultKey, data[0][defaultKey][0] ])
  }

  const [formData, setData] = useState({
    title: '',
    price: '',
    duration: '',
    category: '',
    description: '',
    pictures: []
  });
  const [errors, setErrors] = useState({});
  // 表单验证方法
  const validate = () => {
    if (!formData.title) {
      setErrors({
        title: '标题不能为空！'
      });
      return false;
    } else if (!formData.price) {
      setErrors({
        price: '价格不能为空！'
      });
      return false;
    } else if (!formData.duration) {
      setErrors({
        duration: '发布时长不能为空！'
      });
      return false;
    } else if (!formData.category) {
      setErrors({
        category: '分类不能为空！'
      });
      return false;
    } else if (!formData.description) {
      setErrors({
        description: '详情不能为空！'
      });
      return false;
    } else if (!formData.pictures.length) {
      setErrors({
        pictures: '请上传主图！'
      });
      return false;
    }
    setErrors({})
    return true;
  };
  // 提交表单
  const submit = () => {
    console.log(formData)
    console.log(typeof formData.price)
    console.log(typeof Number(formData.price) !== 'number')

    if (validate()) {
      if (id) {
        axios.put('/goods', {
          id,
          ...formData
        }).then(() => {
          navigation.replace('MyGoods')
        })
      } else {
        axios.post('/goods', {
          ...formData
        }).then(() => {
          navigation.replace('MyGoods')
        })
      }
    }
  }
  const uploadSucess = (data) => {
    console.log('哈哈', data)
    setData({
      ...formData,
      pictures: [...formData.pictures, data]
    })
  }

  const selectCate = () => {
    Picker.init({
      pickerTitleText: '选择分类',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确认',
      pickerData: pickerData,
      selectedValue: selectedValue,
      onPickerConfirm: onPickerConfirm,
      onPickerCancel: data => {
        console.log(data);
      },
      onPickerSelect: onPickerSelect
    });
    Picker.show();
  }
  const onPickerConfirm = (data) => {
    console.log(data)
    const indexName = data[0]
    const childIndexName = data[1]
    const index = categories.findIndex(item => {
      return item.name === indexName
    })
    const childIndex = categories[index].children.findIndex(item => {
      return item.name === childIndexName
    })
    console.log(index, childIndex)
    console.log(categories[index].children[childIndex]._id)
    const target = categories[index].children[childIndex]
    setCategory(target.name)
    setData({
      ...formData,
      category: target._id
    })
  }
  const onPickerSelect = (data) => {
    console.log('onPickerSelect', data)
  }

  return (
    <View style={globalPadding}>
      {/* <Picker
					style={{height: 320}}
					showDuration={300}
					pickerData={pickerData}
					selectedValue={[1, pickerData[1].length + 1]}
					onPickerDone={(pickedValue) => {
						console.log(pickedValue);
					}}
				/> */}
      <FormControl isRequired isInvalid={'title' in errors}>
        <FormControl.Label>标题</FormControl.Label>
        <Input value={formData.title} placeholder='请输入标题' onChangeText={value => setData({
          ...formData,
          title: value
        })} />
        {'title' in errors && <FormControl.ErrorMessage>{errors.title}</FormControl.ErrorMessage>}
      </FormControl>
      <FormControl isRequired isInvalid={'price' in errors}>
        <FormControl.Label>价格</FormControl.Label>
        <Input value={formData.price + ''} placeholder='请输入价格 ' onChangeText={value => setData({
          ...formData,
          price: value
        })} />
        {'price' in errors && <FormControl.ErrorMessage>{errors.price}</FormControl.ErrorMessage>}
      </FormControl>
      <FormControl isRequired isInvalid={'duration' in errors}>
        <FormControl.Label>发布时长</FormControl.Label>
        <Input value={formData.duration + ''} placeholder='请输入发布时长 ' onChangeText={value => setData({
          ...formData,
          duration: value
        })} />
        {'duration' in errors && <FormControl.ErrorMessage>{errors.duration}</FormControl.ErrorMessage>}
      </FormControl>
      <FormControl isRequired isInvalid={'category' in errors}>
        <FormControl.Label>分类</FormControl.Label>
        <TouchableHighlight onPress={selectCate}>
          <Input value={category} editable={false} placeholder='请选择分类' />
        </TouchableHighlight>
        {'category' in errors && <FormControl.ErrorMessage>{errors.category}</FormControl.ErrorMessage>}
      </FormControl>
      <FormControl isRequired isInvalid={'description' in errors}>
        <FormControl.Label>详情</FormControl.Label>
        <Input value={formData.description} placeholder='请输入详情 ' onChangeText={value => setData({
          ...formData,
          description: value
        })} />
        {'description' in errors && <FormControl.ErrorMessage>{errors.description}</FormControl.ErrorMessage>}
      </FormControl>
      <FormControl isRequired isInvalid={'pictures' in errors}>
        <FormControl.Label>主图</FormControl.Label>
        <UploadFile list={formData.pictures} onSuccess={uploadSucess}></UploadFile>
        {'pictures' in errors && <FormControl.ErrorMessage>{errors.pictures}</FormControl.ErrorMessage>}
      </FormControl>
      <Button mt="2" colorScheme="indigo" onPress={submit}>
        提交
      </Button>
      {/* <Picker
        style={{
          height: 300
        }}
        showDuration={300}
        showMask={true}
        pickerData={ [1,2,3,4] }//picker`s value List
        selectedValue={ 3 }//default to be selected value
        onPickerDone={ ()=>{} }//when confirm your choice
      /> */}
    </View>
  )
}

export default UploadGoods

const styles = StyleSheet.create({
  ...globalPadding
})